<template>
  <page-layout>
    <template #title>
      <div class="layout-flex">
        <div class="layout-inline">
          <el-radio-group v-model="viewType" size="medium">
            <el-radio-button
              v-for="(item, index) in viewTypeOptions"
              :key="index"
              :label="item.value"
              :disabled="item.disabled"
              >{{ item.label }}</el-radio-button
            >
          </el-radio-group>
        </div>
        <div class="layout-inline">
          <el-select v-model="queryObj.dataType" placeholder="数据类型" clearable :style="{ width: '100%' }">
            <el-option
              v-for="(item, index) in dataTypeOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </div>
        <div class="layout-inline">
          <el-date-picker
            type="daterange"
            v-model="dateRange"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :style="{ width: '100%' }"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            range-separator="至"
            clearable
          ></el-date-picker>
        </div>
        <div class="layout-inline">
          <el-button type="primary" @click="toExcel">导出</el-button>
        </div>
      </div>
    </template>
    <div class="layout-flex-avg vertical" ref="content1">
      <template v-if="viewType == 1">
        <div class="layout-flex-avg-center" style="height:390px;flex: none;">
          <card-panel>
            <vue-echart :options="option"></vue-echart>
          </card-panel>
        </div>
        <div class="layout-flex-avg-center">
          <card-panel>
            <el-table-block2
              ref="tableBlock2"
              :column="column"
              :data="rows"
              border
              :pagination="true"
              :currentPage="pagination.pageNo"
              :pageSize="pagination.pageSize"
              :total="pagination.total"
              @currentChange="handleCurrentChange"
              :height="tableHeight"
            />
          </card-panel>
        </div>
      </template>
      <template v-else-if="viewType == 2">
        <div class="layout-flex-avg-center">
          <card-panel>
            <vue-echart :options="option"></vue-echart>
          </card-panel>
        </div>
      </template>
      <template v-else>
        <div class="layout-flex-avg-center">
          <card-panel>
            <el-table-block2
              :column="column"
              :data="rows"
              border
              :pagination="true"
              :currentPage="pagination.pageNo"
              :pageSize="pagination.pageSize"
              :total="pagination.total"
              @currentChange="handleCurrentChange"
              :height="tableHeight"
            />
          </card-panel>
        </div>
      </template>
    </div>
  </page-layout>
</template>

<script>
import dayjs from 'dayjs'
import serviceMap from '@/views/theApp/common/serviceMap'
import qs from 'qs'
export default {
  name: 'QueryData',
  props: {
    monitorType: {
      type: String,
      default: 'airtype'
    },
    pointCode: {
      type: String,
      default: ''
    },
    currentRow: {
      type: Object,
      default() {
        return {
          pointCode: '',
          pointName: ''
        }
      }
    }
  },
  computed: {
    option() {
      const rows = this.rows
      const column = this.column
      const legend = []
      const series = {}
      column.forEach(col => {
        if (col.label == '监测时间') {
          return true
        }
        legend.push(col.label)
        series[col.prop] = {
          name: col.label,
          type: 'line',
          stack: 'Total',
          data: []
        }
      })
      const xAxis = []
      rows.forEach(row => {
        xAxis.push(row.monitor_time)
        for (const name in series) {
          series[name].data.push(row[name])
        }
      })
      const series2 = []
      for (const name in series) {
        series2.push(series[name])
      }
      console.log(series)
      return {
        color: [
          '#3D84FF',
          '#6BD5FF',
          '#6ECE65',
          '#179A26',
          '#7681EB',
          '#C890FB',
          '#3D84FF',
          '#3D84FF',
          '#3D84FF',
          '#3D84FF',
          '#3D84FF',
          '#3D84FF',
          '#3D84FF'
        ],
        grid: {
          left: '2%',
          right: '2%',
          top: '12%',
          bottom: '2%',
          containLabel: true
        },
        tooltip: {
          show: true,
          trigger: 'axis',
          position: function(point, params, dom, rect, size) {
            // 其中point为当前鼠标的位置，size中有两个属性：viewSize和contentSize，分别为外层div和tooltip提示框的大小
            var x = point[0] //
            var y = point[1]
            var viewWidth = size.viewSize[0]
            var viewHeight = size.viewSize[1]
            var boxWidth = size.contentSize[0]
            var boxHeight = size.contentSize[1]
            var posX = 0 // x坐标位置
            var posY = 0 // y坐标位置

            if (x < boxWidth) {
              // 左边放不开
              posX = 5
            } else {
              // 左边放的下
              posX = x - boxWidth
            }

            if (y < boxHeight) {
              // 上边放不开
              posY = 5
            } else {
              // 上边放得下
              posY = y - boxHeight
            }

            return [posX, posY]
          }
        },
        legend: {
          // show: false,
          data: legend,
          textStyle: {
            fontSize: 16,
            color: '#ffffff'
          },
          icon: 'circle',
          itemWidth: 8,
          itemHeight: 8
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            fontSize: 13,
            color: '#ffffff'
          },
          boundaryGap: false,
          // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
          data: xAxis,
          axisPointer: {
            type: 'shadow'
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            fontSize: 13,
            color: '#ffffff'
          },
          splitLine: {
            lineStyle: {
              color: '#034b67'
            }
          }
        },
        series: series2
      }
    },
    tableHeight() {
      if (this.viewType == 1) {
        return this.dataTableHeight - 390
      } else if (this.viewType == 1) {
        return this.dataTableHeight - 390
      } else {
        return this.dataTableHeight
      }
    }
  },
  data() {
    const startTime = dayjs()
      .subtract(6, 'month')
      .format('YYYY-MM-DD')
    const endTime = dayjs().format('YYYY-MM-DD')
    return {
      pagination: {
        total: 0,
        pageNo: 1,
        pageSize: 9
      },
      queryObj: {
        monitorType: this.monitorType,
        pointCode: this.pointCode,
        dataType: 3,
        startTime,
        endTime
      },
      dateRange: [startTime, endTime],
      viewType: 1,
      viewTypeOptions: [
        {
          label: '全部',
          value: 1
        },
        {
          label: '图表',
          value: 2
        },
        {
          label: '列表',
          value: 3
        }
      ],
      dataTypeOptions: [
        {
          label: '分钟数据',
          value: 2
        },
        {
          label: '小时数据',
          value: 3
        },
        {
          label: '日数据',
          value: 4
        }
      ],
      column: [],
      rows: [],
      dataTableHeight: 450
    }
  },
  mounted() {
    this.getData()
    this.$nextTick(() => {
      this.handleResize()
    })
  },
  beforeMount() {
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleCurrentChange(v) {
      this.pagination.pageNo = v
      this.getData()
    },
    getQueryObj() {
      const { monitorType, pointCode } = this
      const { pageNo, pageSize } = this.pagination
      const { startTime, endTime } = this.queryObj
      const queryObj = Object.assign({}, this.queryObj, {
        pointCode,
        monitorType,
        pageNo,
        pageSize,
        startTime: startTime == '' ? '' : `${startTime} 00:00:00`,
        endTime: endTime == '' ? '' : `${endTime} 23:59:59`
      })
      return queryObj
    },
    getData() {
      const { monitorType, pointCode } = this
      const queryObj = this.getQueryObj()
      serviceMap[this.monitorType].monitorDataTable(queryObj).then(res => {
        this.pagination.total = res.total
        this.rows = res.rows
        this.$nextTick(() => {
          this.$refs.tableBlock2.doLayout()
        })
      })

      // 历史监测数据表格列
      serviceMap[this.monitorType].monitorDataTableColumn({ monitorType, pointCode }).then(res => {
        this.column = res.map(item => {
          const { text, value } = item
          const column = { label: text, prop: value, align: 'center', width: 200 }
          // column.width = text == '监测时间' ? 150 : 120
          return column
        })
      })
    },
    toExcel() {
      const queryObj = this.getQueryObj()
      queryObj.pointName = this.currentRow.pointName
      const arg = qs.stringify(queryObj)
      const url = `${window.__CTC_ENV__.VUE_APP_BASE_API}/${this.monitorType.replace('type', '')}/monitor/export?${arg}`
      window.open(url, '_blank')
    },
    handleResize() {
      const height = this.$refs.content1.clientHeight
      this.dataTableHeight = height - 120
    }
  },
  watch: {
    pointCode() {
      this.getData()
    },
    dateRange: {
      handler(value) {
        this.queryObj.startTime = (value && value[0]) || ''
        this.queryObj.endTime = (value && value[1]) || ''
      },
      immediate: true
    },
    queryObj: {
      handler() {
        this.getData()
      },
      deep: true
    }
  }
}
</script>

<style scoped></style>
